package com.cykj.web.controller.posbiz;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.cykj.common.core.domain.model.LoginUser;
import com.cykj.common.utils.ServletUtils;
import com.cykj.common.utils.http.HttpUtils;
import com.cykj.framework.web.service.TokenService;
import com.cykj.pos.domain.*;
import com.cykj.pos.domain.dto.*;
import com.cykj.pos.domain.vo.BizPosMachineVo;
import com.cykj.pos.profit.dto.HuaBoDTO;
import com.cykj.pos.profit.dto.PosTerminalDTO;
import com.cykj.pos.profit.dto.VueCallBack;
import com.cykj.pos.profit.dto.VueCallBackDTO;
import com.cykj.pos.service.*;
import com.cykj.system.service.ISysUserService;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.cykj.common.annotation.Log;
import com.cykj.common.core.controller.BaseController;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.enums.BusinessType;
import com.cykj.common.utils.poi.ExcelUtil;
import com.cykj.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 终端设备信息Controller
 *
 * @author ruoyi
 * @date 2021-04-10
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/terminal/posmachine" )
public class BizPosMachineController extends BaseController {

    private final IBizPosMachineService iBizPosMachineService;
    private final IBizPosMachineTemporaryService iBizPosMachineTemporaryService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private final IBizMerchantService iBizMerchantService;
    private HttpUtils HttpRequestUtil;
    private final IBizPosTypeService bizPosTypeService;
    @Autowired
    private   IAllocationRelationService iAllocationRelationService;

    /**
     * 查询终端设备信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(BizPosMachine bizPosMachine) {
        startPage();
        List<BizPosMachine> list = iBizPosMachineService.queryList(bizPosMachine);
        return getDataTable(list);
    }

    /**
     * VUE回调列表
     * @param bizPosMachine
     * @return
     */
    @GetMapping("/listcallback")
    public TableDataInfo listcallback(VueCallBack bizPosMachine) {
        startPage();
        List<VueCallBack> list = iBizPosMachineService.queryListCallBack(bizPosMachine);
        return getDataTable(list);
    }
    /**
     * VUE划拨列表
     * @param bizPosMachine
     * @return
     */
    @PreAuthorize("@ss.hasPermi('terminal:posmachine:list')")
    @GetMapping("/listHb")
    public TableDataInfo listHb(VueCallBack bizPosMachine) {
        startPage();
        List<VueCallBack> list = iBizPosMachineService.queryListHuaBo(bizPosMachine);
        return getDataTable(list);
    }
    /**
     * VUE划拨时详细信息
     */
    @GetMapping(value = "personById/{posId}" )
    public AjaxResult personById(@PathVariable String posId) {
        return AjaxResult.success(iBizPosMachineService.getPersonById(posId));
    }

    /**
     * 获取商户入件详细信息
     */
    @GetMapping(value = "/passSn/{posCode}" )
    public AjaxResult selectBizPosMachinesn(@PathVariable("posCode" ) String posCode) {
        BizPosMachineSyncDTO bizPosMachineSyncDTO= iBizPosMachineService.selectBizPosMachinesn(posCode);
        return AjaxResult.success(bizPosMachineSyncDTO);
    }

    @GetMapping(value = "/posTypeList" )
    public AjaxResult posTypesList() {
        //设备类型
        return AjaxResult.success(bizPosTypeService.list());
    }


    /**
     * 多选划拨
     * @param huaBoDTO
     * @return
     */
    @PutMapping("/personByIdAll")
    public AjaxResult personByIdAll(@RequestBody HuaBoDTO huaBoDTO) {
        VueCallBack vueCallBack=null;
        Long merchId=huaBoDTO.getMerchId();
        Long userId=iBizPosMachineService.selBizMerchantuserid(merchId);
        Long userId1=iBizPosMachineService.selBizMerchantuserid(huaBoDTO.getMerchId());
        for (Long s : huaBoDTO.getPosIds()){
            //获取当前时间
            Date date=new Date();
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time=format.format(date);
            date = null;
            try {
                date = format.parse(time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String time1=format.format(date);

            BizAllocAdjRecords bizAllocAdjRecords=new BizAllocAdjRecords();
            BizPosMachine posCode=iBizPosMachineService.poscode(s);
            bizAllocAdjRecords.setPosId(s);
            bizAllocAdjRecords.setPosCode(posCode.getPosCode());
            bizAllocAdjRecords.setOldUserId(userId1);
            bizAllocAdjRecords.setNewUserId(userId);
            bizAllocAdjRecords.setCreateTime(date);
            bizAllocAdjRecords.setOperateTime(time1);
            bizAllocAdjRecords.setUpdateTime(date);
            HuaBoDTO HuaBoDTO=iBizPosMachineService.getPersonByIds(s,merchId);
            iBizPosMachineService.insertbaarecords(bizAllocAdjRecords);
            // 通过posId查询pos机
        }
        return AjaxResult.success(vueCallBack);
    }
    /**
     * Vue划拨操作
     * @param
     * @return
     */
    @PutMapping("/doTransfer")
    public AjaxResult doTransfer(@RequestBody VueCallBack vueCallBack)
    {
        Long posId=vueCallBack.getPosId();
        Long merchId=vueCallBack.getMerchId();
        BizPosMachine bizPosMachine=iBizPosMachineService.selectposCode(posId);
        /*Long userId=iBizPosMachineService.selBizMerchantuserid(merchId);*/
        /*Long userId1=iBizPosMachineService.selBizMerchantuserid(bizPosMachine.getMerchId());*/
        /*BizAllocAdjRecords bizAllocAdjRecords=new BizAllocAdjRecords();
        bizAllocAdjRecords.setPosId(posId);
        bizAllocAdjRecords.setPosCode(bizPosMachine.getPosCode());
        bizAllocAdjRecords.setOldUserId(userId1);
        bizAllocAdjRecords.setNewUserId(userId);
        //获取当前时间
        Date date=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time=format.format(date);
        date = null;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String time1=format.format(date);

        bizAllocAdjRecords.setCreateTime(date);
        bizAllocAdjRecords.setOperateTime(time1);
        bizAllocAdjRecords.setUpdateTime(date);*/
        VueCallBack vueCallBack1=new VueCallBack();
        vueCallBack1.setPosId(posId);
        vueCallBack1.setMerchId(merchId);
        vueCallBack1.setPosCode(bizPosMachine.getPosCode());
        int CallBack=iBizPosMachineService.doTransfer(vueCallBack1);
        //iBizPosMachineService.doTransferEntry(vueCallBack1);
       /* iBizPosMachineService.insertbaarecords(bizAllocAdjRecords);*/
        return toAjax(CallBack);
    }
    @PutMapping("/clickFunction")
    public void clickFunction()
    {
        iBizPosMachineService.generateAllPosMerchParentRelated();
    }
    /**
     *VUE划拨时所有伙伴列表
     * @param
     * @return
     */
    @GetMapping("/personList")
    public TableDataInfo personList() {
        startPage();
        List<MerchantDTO> list=iBizMerchantService.personList();
        return getDataTable(list);
    }

    //提现代理列表
    @GetMapping("/getALlMerchant")
    public TableDataInfo persogetALlMerchantnList() {
        startPage();
        List<MerchantDTO> list=iBizMerchantService.getALlMerchant();
        return getDataTable(list);
    }
    /**
     * VUE回调
     */
    @GetMapping(value = "/doCallBack/{posCode}" )
    public AjaxResult doCallBack(@PathVariable String posCode) {
        return AjaxResult.success(iBizPosMachineService.doCallBack(posCode));
    }

    /**
     * 多选回调
     * @param
     * @return
     */
    @PutMapping("/doCallBacks")
    public AjaxResult doCallBacks(@RequestBody VueCallBackDTO vueCallBackDTO) {
        for (String s : vueCallBackDTO.getPosCodes()){
            Long posId=iBizPosMachineService.posid(s);
            Long merchId=iBizPosMachineService.selVueCallBackmerchid(posId);
            Long userId=iBizPosMachineService.selBizMerchantuserid(merchId);
            //获取当前时间
            Date date=new Date();
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time=format.format(date);
            date = null;
            try {
                date = format.parse(time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String time1=format.format(date);
            BizAllocAdjRecords bizAllocAdjRecords=new BizAllocAdjRecords();
            bizAllocAdjRecords.setPosId(posId);
            bizAllocAdjRecords.setPosCode(s);
            bizAllocAdjRecords.setOldUserId(userId);
            bizAllocAdjRecords.setNewUserId(new Long(2));
            bizAllocAdjRecords.setCreateTime(date);
            bizAllocAdjRecords.setOperateTime(time1);
            bizAllocAdjRecords.setUpdateTime(date);
            iBizPosMachineService.doCallBacks(s);
            iBizPosMachineService.insertbaarecords(bizAllocAdjRecords);
            // 通过posId查询pos机
        }
        return AjaxResult.success(vueCallBackDTO);
    }


    /**
     * 导出终端设备信息列表
     */
    @PreAuthorize("@ss.hasPermi('terminal:posmachine:export')" )
    @Log(title = "终端设备信息" , businessType = BusinessType.EXPORT)
    @GetMapping("/export" )
    public AjaxResult export(VueCallBack bizPosMachine) {
        List<VueCallBack> list = iBizPosMachineService.queryListExport(bizPosMachine);
        ExcelUtil<VueCallBack> util = new ExcelUtil<VueCallBack>(VueCallBack.class);
        return util.exportExcel(list, "posmachine" );
    }

    /**
     * 下载模板
     * @return
     */
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<BizPosMachine> util = new ExcelUtil<BizPosMachine>(BizPosMachine.class);
        return util.importTemplateExcel("用户设备管理数据");
    }

    /**
     * 导入设备
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @Log(title = "用户设备管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('terminal:posmachine:import')")
    @PostMapping("/importData")
    public AjaxResult importData(@PathVariable("file") MultipartFile file,boolean updateSupport) throws Exception
    {
        ExcelUtil<BizPosMachineTemporaryDTO> util = new ExcelUtil<BizPosMachineTemporaryDTO>(BizPosMachineTemporaryDTO.class);
        List<BizPosMachineTemporaryDTO> posList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = iBizPosMachineTemporaryService.importPosMachine(posList, updateSupport, operName);
        return AjaxResult.success(message);
    }
    /**
     * 获取终端设备信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('terminal:posmachine:query')" )
    @GetMapping(value = "/{posId}" )
    public AjaxResult getInfo(@PathVariable("posId" ) Long posId) {
        return AjaxResult.success(iBizPosMachineService.getById(posId));
    }
    /**
     * 获取终端设备信息详细信息
     */
    @GetMapping(value = "/activate/{posId}" )
    public AjaxResult getInfoid(@PathVariable("posId" ) Long posId) {
        iBizPosMachineService.updataAllId(posId);
        return AjaxResult.success("ok");
    }
    /**
     * @author Wangjiaqi
     * @date 2022/03/02
     * 临时表
     */
    @GetMapping(value = "/temporary" )
    public AjaxResult getTemporary() {
        List<BizPosMachine> bizPosMachine=iBizPosMachineService.selectBizPosMachineAllList();
        return AjaxResult.success(bizPosMachine);
    }

    /**
     * 新增终端设备信息
     */
    @PreAuthorize("@ss.hasPermi('terminal:posmachine:add')" )
    @Log(title = "终端设备信息" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizPosMachine bizPosMachine) {
        return toAjax(iBizPosMachineService.save(bizPosMachine) ? 1 : 0);
    }

    /**
     * 修改终端设备信息
     */
    @PreAuthorize("@ss.hasPermi('terminal:posmachine:edit')" )
    @Log(title = "终端设备信息" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizPosMachine bizPosMachine) {
        return toAjax(iBizPosMachineService.updateById(bizPosMachine) ? 1 : 0);
    }

    /**
     * 删除终端设备信息
     */
    @Log(title = "终端设备信息" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{posIds}" )
    public AjaxResult remove(@PathVariable Long[] posIds) {
        return toAjax(iBizPosMachineService.removeByIds(Arrays.asList(posIds)) ? 1 : 0);
    }


    /**
     * 设备划拨
     */
//    @PreAuthorize("@ss.hasPermi('terminal:posmachine:transfer')" )
//    @Log(title = "终端设备信息" , businessType = BusinessType.UPDATE)
//    @PutMapping
//    public AjaxResult transfer(@RequestBody BizPosMachine bizPosMachine) {
//        return toAjax(iBizPosMachineService.updateById(bizPosMachine) ? 1 : 0);
//    }


    /**
     * 批量入库导入模板
     * @return
     */
    @GetMapping("/importPospTemplate")
    public AjaxResult importPospTemplate()
    {
        ExcelUtil<BizPosMachineVo> util = new ExcelUtil<BizPosMachineVo>(BizPosMachineVo.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 导入
     * @param
     * @return
     */
    @PostMapping("/pospsInsert")
    public AjaxResult pospsInsert(@PathVariable("file") MultipartFile file,
                                  boolean updateSupport,String merchName,String posTypeId,String posName,String deviceType) throws Exception
    {
        ExcelUtil<BizPosMachineVo> util = new ExcelUtil<BizPosMachineVo>(BizPosMachineVo.class);
        List<BizPosMachineVo> posList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
//        String message = iBizPosMachineTemporaryService.importPosMachine(posList, updateSupport, operName);
        return AjaxResult.success();
    }


    // app 划拨
    @ApiOperation("划拨设备")
    @PostMapping("/allocation/sn")
    public AjaxResult allocationSn(@RequestBody AllocationRelation allocationRelation){
        return iBizPosMachineService.allocationSn(allocationRelation);
    }


    // app 品牌下的机器  按渠道分
    @PostMapping("/posMachine/list")
    public AjaxResult posMachineList(@RequestBody BizPosMachine bizPosMachine){
        return iBizPosMachineService.posMachineList(bizPosMachine);
    }


    // app 划拨进去显示的设备列表
    @PostMapping("/posMachine/trans/list")
    public AjaxResult posMachineTransList(@RequestBody PosTerminalDTO posTerminalDTO){
        return iBizPosMachineService.posMachineTransList(posTerminalDTO);
    }


    // app  区间查询
    @PostMapping("/posMachine/interval/list")
    public AjaxResult posMachineIntervalList(@RequestBody PosTerminalDTO posTerminalDTO){
        return iBizPosMachineService.posMachineIntervalList(posTerminalDTO);
    }


    //app 划拨时 押金和流量费的区间
    @PostMapping("/posMachine/interval/service/flow")
    public AjaxResult posMachineIntervalServiceFlow(@RequestBody PosTerminalDTO posTerminalDTO){
        return iBizPosMachineService.posMachineIntervalServiceFlow(posTerminalDTO);
    }


    // app  划拨记录
    @PostMapping("/posMachine/transfer/records")
    public AjaxResult posMachineTransferRecords(@RequestBody BizTransferRecords bizTransferRecords){
        return iBizPosMachineService.posMachineTransferRecords(bizTransferRecords);
    }

    // app 未激活设备列表
    @PostMapping("/posMachine/unActive/list")
    public AjaxResult posMachineUnActiveList(@RequestBody BizPosMachine bizPosMachine){
        return iBizPosMachineService.posMachineUnActiveList(bizPosMachine);
    }

    //app 渠道切换
    @PostMapping("/channel/list")
    public AjaxResult channelList(){
        return iBizPosMachineService.channelList();
    }


    //app 划拨明细
    @PostMapping("/posMachine/transfer/detail")
    public AjaxResult posMachineTransferDetail(@RequestBody BizTransferRecords bizTransferRecords){
        return iBizPosMachineService.posMachineTransferDetail(bizTransferRecords);
    }

    //app 素材库类型
    @PostMapping("/picture/back/channels")
    public AjaxResult pictureBackChannels(){
        return iBizPosMachineService.pictureBackChannels();
    }

    //app  素材库
    @PostMapping("/picture/store")
    public AjaxResult pictureStore(@RequestBody BizPictureStore bizPictureStore){
        return iBizPosMachineService.pictureStore(bizPictureStore);
    }


    // app 回调 列表
    @PostMapping("/back/posCode/list")
    public AjaxResult backPosCodeList(@RequestBody PosTerminalDTO posTerminalDTO){
        return iBizPosMachineService.backPosCodeList(posTerminalDTO);
    }

    // app 回调 列表 区间查询
    @PostMapping("/back/posCode/interval/list")
    public AjaxResult backPosCodeIntervalList(@RequestBody PosTerminalDTO posTerminalDTO){
        return iBizPosMachineService.backPosCodeIntervalList(posTerminalDTO);
    }

    // app 回调
    @PostMapping("/back/posCode")
    public AjaxResult backPosCode(@RequestBody AllocationRelation allocationRelation){
        return iBizPosMachineService.backPosCode(allocationRelation);
    }

    @PostMapping("/querySettlementTemp")
    public AjaxResult querySettlementTemp(@RequestBody BizPosMachine bizPosMachine){
        return iBizPosMachineService.querySettlementTemp(bizPosMachine);
    }

}
